package cn.yanhu.kuwanapp.welfare.ad.gdt

import android.app.Activity
import android.content.Context
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import cn.yanhu.kuwanapp.utils.Config
import cn.yanhu.kuwanapp.utils.ext.logcom
import cn.yanhu.kuwanapp.utils.ext.showToast
import cn.yanhu.kuwanapp.welfare.ad.AdSlotType
import cn.yanhu.kuwanapp.welfare.ad.IAdProcess
import com.qq.e.ads.interstitial2.UnifiedInterstitialAD
import com.qq.e.ads.interstitial2.UnifiedInterstitialADListener
import com.qq.e.ads.rewardvideo.RewardVideoAD
import com.qq.e.ads.rewardvideo2.ExpressRewardVideoAD
import com.qq.e.ads.rewardvideo2.ExpressRewardVideoAdListener
import com.qq.e.comm.util.AdError
import com.qq.e.comm.util.VideoAdValidity


/**
 *广点通广告
 *@author woochen
 *@time 2020-01-04 18:22
 */
class GdtAdProcess : IAdProcess {
    private var rewardVideoAD: RewardVideoAD? = null
    private var mExpressRewardVideoAD: ExpressRewardVideoAD? = null
    private var adLoaded: Boolean = false //广告加载成功标志
    private var videoCached: Boolean = false
    override var mAdLoadLifecycle: IAdProcess.AdLoadLifecycle? = null
    private var iad: UnifiedInterstitialAD? = null //腾讯插屏广告


    override fun loadAd(context: Context,
                        slotType: Int,
                        codeId: String,
                        isPortation: Boolean,
                        innerCodeId: String,
                        containerView: ViewGroup?,
                        adTimeOut: Int) {

        when (slotType) {
            AdSlotType.AD_INTERSTITIAL -> {
                loadInteracteAd(context, codeId, innerCodeId)
            }
            AdSlotType.AD_VIDEO -> {
                loadRewardVideo(context, codeId, isPortation, innerCodeId)
            }
            AdSlotType.AD_FULLSCREEN -> {
                //                loadFullScreenVideo(context,codeId,isPortation,innerCodeId)
            }
        }

    }


    /**
     * 加载插屏广告
     */
    private fun loadInteracteAd(context: Context, codeId: String, innerCodeId: String) {
        mAdLoadLifecycle?.adLoadStart(innerCodeId)
        val listener: UnifiedInterstitialADListener = object : UnifiedInterstitialADListener {
            override fun onADExposure() {
                logcom("gdt-loadInteracteAd:onADExposure")
            }

            override fun onVideoCached() {
                logcom("gdt-onVideoCached")
            }

            override fun onADOpened() {
                mAdLoadLifecycle?.adShowed(innerCodeId)
                logcom("gdt-loadInteracteAd:onADOpened")
            }

            override fun onADClosed() {
                mAdLoadLifecycle?.adDismissed(innerCodeId)
                releaseResource()
            }

            override fun onRenderSuccess() {

            }

            override fun onRenderFail() {

            }

            override fun onADLeftApplication() {
                logcom("gdt-onADLeftApplication")
            }

            override fun onADReceive() {
                logcom("gdt-loadInteracteAd:onADReceive")
                iad?.show()
            }

            override fun onNoAD(error: AdError?) {
                logcom("gdt-loadInteracteAd:${error?.errorCode} ${error?.errorMsg}")
                mAdLoadLifecycle?.adLoadFail(innerCodeId, "gdt:${error?.errorCode},${error?.errorMsg}")
                releaseResource()
            }

            override fun onADClicked() {
                logcom("gdt-loadInteracteAd:onADClicked")
                mAdLoadLifecycle?.adClicked(innerCodeId)
            }
        }
        if (context is Activity) {
            iad = UnifiedInterstitialAD(context, Config.YLH_APP_ID, codeId, listener)
        } else if (context is Fragment) {
            iad = UnifiedInterstitialAD(context.activity, Config.YLH_APP_ID, codeId, listener)

        }
        iad?.loadAD()

    }

    /**
     * 加载激励视频
     */
     private fun loadRewardVideo(context: Context, codeId: String, portation: Boolean, innerCodeId: String) {
         mAdLoadLifecycle?.adLoadStart(innerCodeId)
         // 1. 初始化激励视频广告
         mExpressRewardVideoAD = ExpressRewardVideoAD(context, codeId, object :
             ExpressRewardVideoAdListener {
             override fun onClick() {
                 logcom("gdt:onADClick")
                 mAdLoadLifecycle?.adClicked(innerCodeId)
             }

             override fun onVideoCached() {
                 logcom("gdt:onVideoCached")
                 videoCached = true
                 showAd(context, AdSlotType.AD_VIDEO)
             }

             override fun onExpose() {
                 logcom("gdt:onADExpose")
                 mAdLoadLifecycle?.aDExpose(innerCodeId)
             }

             override fun onReward(p0: MutableMap<String, Any>?) {
                 logcom("gdt:onReward")
                 mAdLoadLifecycle?.adReward(innerCodeId)
             }

             override fun onVideoComplete() {
                 logcom("gdt:onVideoComplete")
                 mAdLoadLifecycle?.adPlayComplete(innerCodeId)
             }

             override fun onClose() {
                 logcom("gdt:onADClose")
                 mAdLoadLifecycle?.adDismissed(innerCodeId)
                 releaseResource()
             }

             override fun onError(p0: AdError?) {
                 logcom("gdt:${p0?.errorCode},${p0?.errorMsg}")
                 mAdLoadLifecycle?.adLoadFail(innerCodeId,"gdt:code=${p0?.errorCode},${p0?.errorMsg}")
                 releaseResource()
             }

             override fun onAdLoaded() {
                 adLoaded = true
                 logcom("gdt:onADLoad")
                 mAdLoadLifecycle?.adLoadComplete(innerCodeId)

             }

             override fun onShow() {
                 logcom("gdt:onADShow")
                 mAdLoadLifecycle?.adPlayStart(innerCodeId)
             }
         })
         adLoaded = false
         videoCached = false
         // 2. 加载激励视频广告
         mExpressRewardVideoAD?.loadAD()
     }

    /**
     * 资源回收
     */
    private fun releaseResource() {
        mAdLoadLifecycle = null
        rewardVideoAD = null
        mExpressRewardVideoAD = null
        adLoaded = false //广告加载成功标志
        videoCached = false
        iad?.destroy()
        iad = null

    }

    override fun showAd(context: Context, slotType: Int) {
        when (slotType) {
            AdSlotType.AD_INTERSTITIAL -> {

            }
            AdSlotType.AD_VIDEO -> {
                // 3. 展示激励视频广告
                 if (videoCached && mExpressRewardVideoAD != null){
                     val validity: VideoAdValidity? = mExpressRewardVideoAD?.checkValidity()
                     when (validity) {
                         VideoAdValidity.SHOWED -> {
                             showToast("广告已经展示过！")
                             return
                         }
                         VideoAdValidity.NONE_CACHE -> {
                             showToast("广告素材未缓存成功！")
                             return
                         }
                         VideoAdValidity.OVERDUE -> {
                             showToast("广告已经过期！")
                             return
                         }
                         VideoAdValidity.VALID -> {
                             logcom("广告有效")

                         }
                     }
                     mExpressRewardVideoAD?.showAD(null)
                 }

            }
            AdSlotType.AD_FULLSCREEN -> {

            }
        }
    }

    override fun release() {
        releaseResource()
    }
}